// pages/binddevice/binddevice.js
const app = getApp();
const { deviceApi } = require('../../services/api');

Page({
  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {},
    isLoading: false,
    devices: [],
    boundDevices: [],
    errorMessage: '',
    showError: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('绑定设备页面加载');
    
    // 获取用户信息
    const userInfo = wx.getStorageSync('userInfo');
    if (userInfo) {
      this.setData({
        userInfo: userInfo
      });
    }
    
    // 加载设备列表
    this.loadDevices();
  },

  /**
   * 加载设备列表
   */
  loadDevices: function() {
    this.setData({ isLoading: true, showError: false });
    
    // 模拟获取设备列表
    setTimeout(() => {
      // 模拟数据
      const devices = [
        { id: '121', name: '设备2', model: '121', status: '未绑定' },
        { id: '122', name: '设备3', model: '122', status: '未绑定' },
        { id: '123', name: '设备4', model: '123', status: '未绑定' }
      ];
      
      const boundDevices = [
        { id: '111', name: '设备1', model: '111', status: '已绑定', battery: 69 }
      ];
      
      this.setData({
        devices: devices,
        boundDevices: boundDevices,
        isLoading: false
      });
    }, 1000);
  },

  /**
   * 绑定设备
   */
  bindDevice: function(e) {
    const deviceId = e.currentTarget.dataset.id;
    console.log('绑定设备:', deviceId);
    
    this.setData({ isLoading: true });
    
    // 模拟绑定设备
    setTimeout(() => {
      // 更新设备列表
      const devices = this.data.devices.filter(device => device.id !== deviceId);
      const boundDevice = this.data.devices.find(device => device.id === deviceId);
      
      if (boundDevice) {
        boundDevice.status = '已绑定';
        boundDevice.battery = 100;
        
        this.setData({
          devices: devices,
          boundDevices: [...this.data.boundDevices, boundDevice],
          isLoading: false
        });
        
        wx.showToast({
          title: '设备绑定成功',
          icon: 'success'
        });
      }
    }, 1500);
  },

  /**
   * 返回上一页
   */
  navigateBack: function() {
    wx.navigateBack({
      fail: function() {
        wx.switchTab({
          url: '../airquality/airquality'
        });
      }
    });
  }
})